package com.beiing.tianshuai.tianshuai.message.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.GroupMemberAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.GroupDetailsBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.message.presenter.GroupDetailsPresenter;
import com.beiing.tianshuai.tianshuai.message.view.GroupDetailsViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.PersonalDataCardActivity;
import com.beiing.tianshuai.tianshuai.nim.session.activity.MessageHistoryActivity;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.kyleduo.switchbutton.SwitchButton;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.SimpleCallback;
import com.netease.nim.uikit.business.session.helper.MessageListPanelHelper;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.impl.cache.TeamDataCache;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.constant.TeamFieldEnum;
import com.netease.nimlib.sdk.team.constant.TeamInviteModeEnum;
import com.netease.nimlib.sdk.team.constant.TeamMessageNotifyTypeEnum;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class GroupDetailsActivity extends BaseActivity implements GroupDetailsViewImpl {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.rv_group_members)
    RecyclerView mRvGroupMembers;
    @BindView(R.id.btn_all_members)
    TextView mBtnAllMembers;
    @BindView(R.id.tv_group_name)
    TextView mTvGroupName;
    @BindView(R.id.tv_group_notice)
    TextView mTvNotice;
    @BindView(R.id.invited_sb_md)
    SwitchButton mInvitedSbMd;
    @BindView(R.id.sb_md)
    SwitchButton mSbMd;
    @BindView(R.id.btn_quit_group)
    TextView mBtnQuitGroup;
    @BindView(R.id.ll_group_name)
    RelativeLayout mLlGroupName;
    @BindView(R.id.ll_allow_member_invited)
    RelativeLayout mLlAllowMemberInvited;
    @BindView(R.id.ll_group_announcement)
    RelativeLayout mLlGroupAnnouncement;
    @BindView(R.id.ll_group_avatar)
    RelativeLayout mLlGroupAvatar;
    @BindView(R.id.ll_group_desc)
    RelativeLayout mLlGroupDesc;
    @BindView(R.id.ll_clear_chatting_records)
    RelativeLayout mLlClearRecords;
    @BindView(R.id.ll_close_notification)
    RelativeLayout mLlCloseNotification;
    @BindView(R.id.tv_group_desc)
    TextView mTvGroupDesc;
    @BindView(R.id.civ_group_avatar)
    CircleImageView mCivGroupAvatar;
    @BindView(R.id.tv_group_number)
    TextView mTvGroupNumber;
    @BindView(R.id.ll_my_group_name)
    RelativeLayout mRlMyGroupName;
    @BindView(R.id.tv_my_group_name)
    TextView mTvGroupNickName;
    @BindView(R.id.ll_my_group_msg_history)
    RelativeLayout mRlMyGroupMsgHistory;

    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private static final String TAG = "GroupDetailsActivity";
    private Context mContext;
    private String mGroupId;
    private GroupMemberAdapter mAdapter;
    private GroupDetailsBean.DataBean.NumberBean.GroupBean mGroup;
    private boolean isOwner;
    private List<GroupDetailsBean.DataBean.NumberBean.UserBean> mUser;
    private GroupDetailsPresenter mPresenter;
    private String mUid;
    private String mPhotoPath;
    private File mUpdateAvatar;

    public static void start(Context context, String groupId) {
        Intent intent = new Intent(context, GroupDetailsActivity.class);
        intent.putExtra("groupId", groupId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_details;
    }

    @Override
    protected void init() {
        mContext = this;
        mUid = UserInfoBean.getUid(mContext);
        initData();
        initToolbar();
        initRecyclerView();
    }

    private void initData() {
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("groupId");
    }

    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarTvTitle.setText("群聊");
    }

    private void initGroup() {
        TeamDataCache.getInstance().fetchTeamById(mGroupId, new SimpleCallback<Team>() {
            @Override
            public void onResult(boolean success, Team result, int code) {
                if (success) {
                    String creator = result.getCreator();
                    if (TextUtils.equals(creator, mUid)) {
                        isOwner = true;
                        if (mLlAllowMemberInvited != null) {
                            mLlAllowMemberInvited.setVisibility(View.VISIBLE);
                        }
                        if (mBtnQuitGroup != null) {
                            mBtnQuitGroup.setText("解散并退出群聊");
                        }
                    } else {
                        isOwner = false;
                        if (mLlAllowMemberInvited != null) {
                            mLlAllowMemberInvited.setVisibility(View.GONE);
                        }
                        if (mBtnQuitGroup != null) {
                            mBtnQuitGroup.setText("退出群聊");
                        }
                    }
                    initPresenter();
                    int value = result.getMessageNotifyType().getValue();
                    mSbMd.setChecked(value == TeamMessageNotifyTypeEnum.Mute.getValue());
                    mSbMd.setClickable(true);
                }
            }
        });
    }

    private void initRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 5);
        /*
         *  设置SpanSizeLookup，它将决定view会横跨多少列。这个方法是为RecyclerView添加Header和Footer的关键。
         *  当判断position指向的View为Header或者Footer时候，返回总列数 lm.getSpanCount() ,即可让其独占一行。
         */
        mRvGroupMembers.setNestedScrollingEnabled(false);
        mRvGroupMembers.setLayoutManager(gridLayoutManager);
        //绘制item间的分割线，
        mRvGroupMembers.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(6, 10, 6, 10);
            }
        });
        mRvGroupMembers.setItemAnimator(new DefaultItemAnimator());
    }

    private void initPresenter() {
        mPresenter = new GroupDetailsPresenter(this);
        mPresenter.getGroupDetailsRequestResponse(
                mUid,
                mGroupId
        );
    }

    private void initListener() {
        // 查找聊天记录
        mRlMyGroupMsgHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageHistoryActivity.start(mContext, mGroupId, SessionTypeEnum.Team); // 漫游消息查询
            }
        });

        //清除聊天记录
        mLlClearRecords.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "清除聊天记录将不可恢复，确定要删除么？",
                        new CustomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    // 删除与某个聊天对象的全部消息记录
                                    NIMClient.getService(MsgService.class).clearChattingHistory(mGroupId, SessionTypeEnum.Team);
                                    MessageListPanelHelper.getInstance().notifyClearMessages(mGroupId);
                                    showShortText("清除成功");
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });

        //修改群简介
        mLlGroupDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGroup != null && isOwner) {
                    Intent toEditNotice = new Intent(mContext, EditGroupNoticeActivity.class);
                    toEditNotice.putExtra("groupName", mTvGroupName.getText().toString());
                    toEditNotice.putExtra("groupId", mGroupId);
                    toEditNotice.putExtra("groupNotice", mGroup.getGroupnotice());
                    toEditNotice.putExtra("groupDesc", mGroup.getGroupdesc());
                    toEditNotice.putExtra("gId", mGroup.getId());
                    toEditNotice.putExtra("type", AppConstant.GROUP_DESC);
                    startActivityForResult(toEditNotice, AppConstant.EDIT_GROUP_DESC);
                }
            }
        });

        //修改群公告
        mLlGroupAnnouncement.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (mGroup != null && isOwner) {
                    Intent toEditNotice = new Intent(mContext, EditGroupNoticeActivity.class);
                    toEditNotice.putExtra("groupName", mTvGroupName.getText().toString());
                    toEditNotice.putExtra("groupId", mGroupId);
                    toEditNotice.putExtra("groupNotice", mGroup.getGroupnotice());
                    toEditNotice.putExtra("groupDesc", mGroup.getGroupdesc());
                    toEditNotice.putExtra("gId", mGroup.getId());
                    toEditNotice.putExtra("type", AppConstant.GROUP_NOTICE);
                    startActivityForResult(toEditNotice, AppConstant.EDIT_GROUP_NOTICE);
                }
            }
        });

        //群主修改群头像
        mLlGroupAvatar.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (mGroup != null && isOwner) {
                    checkSelfPermission();
                }
            }
        });

        //退出群|解散群
        mBtnQuitGroup.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "确定要删除该群聊吗？",
                        new CustomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    quitGroup();
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });

        //成员条目点击事件
        mAdapter.setListener(new GroupMemberAdapter.OnClickListener() {
            @Override
            public void onItemClickListener(int position, String uid) {
                Intent intent = new Intent(mContext, PersonalDataCardActivity.class);
                intent.putExtra("uid", uid);
                startActivity(intent);
            }

            @Override
            public void onAddUserClickListener() {
                if (mGroup != null) {
                    switch (mGroup.getStatus()) {
                        case "0":
                            toAddMembers();
                            break;
                    }
                }
            }

            @Override
            public void onDelUserClickListener() {
                if (mGroup != null) {
                    toDelMembers();
                }
            }
        });

        //查看全部群成员
        mBtnAllMembers.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(mContext, GroupAllMembersActivity.class);
                intent.putExtra("members", (Serializable) mUser);
                startActivity(intent);
            }
        });

        //屏蔽群消息
        mSbMd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                TeamMessageNotifyTypeEnum type;
                if (b) {
                    type = TeamMessageNotifyTypeEnum.Mute;
                } else {
                    type = TeamMessageNotifyTypeEnum.All;
                }
                DialogMaker.showProgressDialog(GroupDetailsActivity.this, getString(com.netease.nim.uikit.R.string.empty), true);
                NIMClient.getService(TeamService.class).muteTeam(mGroupId, type).setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                        DialogMaker.dismissProgressDialog();
                    }

                    @Override
                    public void onFailed(int code) {
                        DialogMaker.dismissProgressDialog();
                        showShortText("操作失败");
                    }

                    @Override
                    public void onException(Throwable exception) {
                        DialogMaker.dismissProgressDialog();
                    }
                });
            }
        });

        //群主修改邀请权限
        mInvitedSbMd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGroup != null && isOwner) {
                    TeamInviteModeEnum type = mInvitedSbMd.isChecked() ?
                            TeamInviteModeEnum.All : TeamInviteModeEnum.Manager;
                    updateInviteMode(type);
                    mPresenter.getEditInvitedRootResult(mUid, mGroup.getId());
                }
            }
        });

        //修改群昵称
        mLlGroupName.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (mGroup != null && isOwner) {
                    Intent toEditName = new Intent(mContext, EditGroupNameActivity.class);
                    toEditName.putExtra("groupName", mTvGroupName.getText().toString());
                    toEditName.putExtra("groupId", mGroupId);
                    toEditName.putExtra("groupNotice", mGroup.getGroupnotice());
                    toEditName.putExtra("groupDesc", mGroup.getGroupdesc());
                    toEditName.putExtra("gId", mGroup.getId());
                    startActivityForResult(toEditName, AppConstant.EDIT_GROUP_NAME);
                }
            }
        });

        //修改我的群昵称
        mRlMyGroupName.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (mGroup != null) {
                    Intent toEditName = new Intent(mContext, EditMyGroupNickNameActivity.class);
                    startActivityForResult(toEditName, AppConstant.EDIT_MY_GROUP_NICK_NAME);
                }
            }
        });

        //返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 退出群聊
     */
    private void quitGroup() {
        if (isOwner) {
            dismissTeam();
        } else {
            quitTeam();
        }
    }

    /**
     * 非群主退出群
     */
    private void quitTeam() {
        mPresenter.getQuitGroupResult(
                mUid,
                mGroup.getId(),
                mGroup.getGroupid()
        );
    }

    /**
     * 群主解散群(直接退出)
     */
    private void dismissTeam() {
        mPresenter.getDismissGroupResult(
                mUid,
                mGroup.getId(),
                mGroup.getGroupid()
        );
    }

    /**
     * 更新邀请他人权限
     *
     * @param type 邀请他人类型
     */
    private void updateInviteMode(final TeamInviteModeEnum type) {
        DialogMaker.showProgressDialog(this, getString(com.netease.nim.uikit.R.string.empty));
        NIMClient.getService(TeamService.class).updateTeam(mGroupId, TeamFieldEnum.InviteMode, type).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                DialogMaker.dismissProgressDialog();
                Toast.makeText(GroupDetailsActivity.this, com.netease.nim.uikit.R.string.update_success, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(int code) {
                DialogMaker.dismissProgressDialog();
                Toast.makeText(GroupDetailsActivity.this, String.format(getString(com.netease.nim.uikit.R.string.update_failed), code), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable exception) {
                DialogMaker.dismissProgressDialog();
            }
        });
    }

    private void toDelMembers() {
        Intent toDelMembers = new Intent(mContext, GroupDelMembersActivity.class);
        toDelMembers.putExtra("members", (Serializable) mUser);
        toDelMembers.putExtra("easeGId", mGroupId);
        toDelMembers.putExtra("gId", mGroup.getId());
        startActivity(toDelMembers);
    }

    private void toAddMembers() {
        Intent toAddMembers = new Intent(mContext, GroupAddMembersActivity.class);
        toAddMembers.putExtra("members", (Serializable) mUser);
        toAddMembers.putExtra("easeGId", mGroupId);
        toAddMembers.putExtra("gId", mGroup.getId());
        toAddMembers.putExtra("isOwner", isOwner ? "true" : "false");
        startActivity(toAddMembers);
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(GroupDetailsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(
                        GroupDetailsActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS
                );
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            mUpdateAvatar = new File(outfile);
                            mPresenter.getUpdateAvatarResult(mUid, mGroup.getId(), mUpdateAvatar);
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(true)                                         // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(GroupDetailsActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        switch (resultCode) {
            case AppConstant.EDIT_GROUP_NAME:
                String groupName = data.getStringExtra("groupName");
                mTvGroupName.setText(groupName);
                break;
            case AppConstant.EDIT_GROUP_NOTICE:
                String groupNotice = data.getStringExtra("groupNotice");
                mTvNotice.setText(groupNotice);
                break;
            case AppConstant.EDIT_MY_GROUP_NICK_NAME:
                String myGroupNickName = data.getStringExtra("data");
                mTvGroupNickName.setText(myGroupNickName);
                NIMClient.getService(TeamService.class).updateMyTeamNick(mGroupId, myGroupNickName);
                break;
        }
    }

    @Override
    protected void onResume() {
        initGroup();
        super.onResume();
    }

    @Override
    public void onDismissGroupSuccess(CodeBean bean) {
        int code = bean.getCode();
        if (code == 200) {
            finish();
        } else if (code == 401) {
            showShortText("该群组已不存在");
        }
    }

    @Override
    public void onQuitGroupSuccess(CodeBean bean) {
        int code = bean.getCode();
        if (code == 200) {
            Intent intent = new Intent();
            intent.putExtra("isQuit", true);
            setResult(AppConstant.TO_GROUP_DETAILS, intent);
            finish();
        } else if (code == 401) {
            showShortText("该群组已不存在");
        }
    }

    @Override
    public void onUpdateAvatarSuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            showShortText("修改成功");
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override(350, 350)
                    .centerCrop();
            Glide.with(mContext.getApplicationContext())
                    .load(mUpdateAvatar)
                    .apply(options)
                    .into(mCivGroupAvatar);
        } else {
            showShortText("修改失败");
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在加载，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(GroupDetailsBean bean) {
        if (bean.getCode() == 200) {
            //群成员信息
            mUser = bean.getData().getNumber().getUser();
            mToolbarTvTitle.setText(MessageFormat.format("群聊({0})", mUser.size()));
            List<GroupDetailsBean.DataBean.NumberBean.UserBean> userShow = new ArrayList<>();
            for (int i = 0; i < mUser.size() && i < 30; i++) {
                userShow.add(mUser.get(i));
            }
            //群资料
            mGroup = bean.getData().getNumber().getGroup();
            if (mAdapter == null) {
                mAdapter = new GroupMemberAdapter(mContext, mGroup.getStatus(), isOwner);
                mRvGroupMembers.setAdapter(mAdapter);
                initListener();
            }
            mAdapter.updateData(userShow);
            String groupName = mGroup.getGroupname();
            String groupNotice = mGroup.getGroupnotice();
            String groupDesc = mGroup.getGroupdesc();
            String groupNum = mGroup.getGroupnum();
            String status = mGroup.getStatus();
            String avatar = mGroup.getGroupphoto();
            mTvGroupName.setText(groupName);
            mTvNotice.setText(groupNotice);
            mTvGroupDesc.setText(groupDesc);
            mTvGroupNumber.setText(groupNum);
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override(350, 350)
                    .centerCrop();
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(avatar) ?
                            R.mipmap.default_avatar :
                            HttpRequestConstant.GROUP_PIC_HEAD + avatar)
                    .apply(options)
                    .into(mCivGroupAvatar);
            switch (status) {
                case "0":
                    mInvitedSbMd.setChecked(true);
                    break;
                case "1":
                    mInvitedSbMd.setChecked(false);
                    break;
            }
            mInvitedSbMd.setClickable(true);

            NimUIKit.getTeamProvider().fetchTeamMemberList(mGroupId, new SimpleCallback<List<TeamMember>>() {
                @Override
                public void onResult(boolean success, List<TeamMember> members, int code) {
                    if (success && members != null && !members.isEmpty()) {
                        updateTeamMember(members);
                    }
                }
            });

        } else {
            showShortText("哎呀，加载出错啦！");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    private void updateTeamMember(final List<TeamMember> m) {
        if (m != null && m.isEmpty()) {
            return;
        }
        updateTeamBusinessCard(m);
    }

    /**
     * 更新我的群名片
     *
     * @param m 群成员列表
     */
    private void updateTeamBusinessCard(List<TeamMember> m) {
        for (TeamMember teamMember : m) {
            if (teamMember != null && teamMember.getAccount().equals(NimUIKit.getAccount())) {
                mTvGroupNickName.setText(teamMember.getTeamNick() != null ? teamMember.getTeamNick() : "");
            }
        }
    }
}
